package com.example.spider.proxy.core.distinct;

import com.example.spider.util.FileBasedCollection;
import org.shoulder.core.util.AddressUtils;

import java.util.concurrent.ConcurrentSkipListSet;

/**
 * 用于分析ip、port分布
 */
public class FileBasedIpPortDistincter implements IpPortDistincter {

    private final FileBasedCollection<ConcurrentSkipListSet<String>, String> allIpPort;

    public FileBasedIpPortDistincter(FileBasedCollection<ConcurrentSkipListSet<String>, String> allIpPort) {
        this.allIpPort = allIpPort;
    }

    @Override
    public boolean add(String ip, int port) {
        if (!AddressUtils.isIpv4(ip) || !AddressUtils.isPort(port)) {
            return false;
        }
        return allIpPort.add(formatIpPort(ip, port));
    }

    @Override
    public boolean contains(String ip, int port) {
        return allIpPort.contains(formatIpPort(ip, port));
    }

    private String formatIpPort(String ip, int port) {
        return ip + ":" + port;
    }
}
